<?php

namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
use App\Service\VendorClient\GaoDeAddressApi\GaoDeAddressApiClient;
use App\Service\Code\Normal;
use Hyperf\DbConnection\Db;
use App\Service\CacheService\CacheProviderService;
class TemplateDeliveryArea extends BasePssModel
{
    public $table = 'template_delivery_area';
    
    //用户下单地址高德解析缓存地址
    const USER_ADDRESS_CACHE_KEY = 'user_address_cache_key';
    
    /**
     * 获取运费模板区域分组
     * @param array $tpl_ids
     */
    public function getGoodsTemplateByIds( array $tpl_ids = [] )
    {
        $tpl_ids = array_unique($tpl_ids);
        $tpl_ids = array_filter($tpl_ids);
        if( empty($tpl_ids) ) {
            return [];
        }
        
        $list = $this
        ->select([
            'template_delivery_area.id as tda_id',
            'template_delivery_area.template_id',
            'template_delivery_area.is_all_country',
            'template_delivery_area.init_weight',
            'template_delivery_area.init_money',
            'template_delivery_area.increase_weight',
            'template_delivery_area.increase_money',
            Db::raw("IFNULL(tdal.area_id,0) as tda_area_id")
        ])
        ->leftJoin('template_delivery_area_list as tdal', 'tdal.tda_id', '=', 'template_delivery_area.id')
        ->whereIn('template_delivery_area.template_id',$tpl_ids)
        ->get()
        ->toArray();
        if( empty($list) ) {
            return [];
        }
        $list_map = [];
        foreach ($list as & $item )
        {
            //运费最高单价  = 首重价格 + 续重价格单价/KG
            $item['freight_all'] = bcadd((string)$item['init_money'], (string)$item['increase_money'],2) * 100;
            if( $item['is_all_country'] ) {
                $list_map[$item['template_id']]['is_all_country'] = $item;
            } else {
                $list_map[$item['template_id']]['is_other_country'][$item['tda_area_id']] = $item;
            }
            unset($item);
        }
        return $list_map;
    }

    /**
     * 更具模板和重量计算金额
     * @param array $template
     * @param $weight
     */
    public function getFreightMoneyByTemplateAndWeight( array $template = [] , $weight = 0 ) 
    {
        if (empty($template)){
            return 0;
        }
        $init_weight        = $template['init_weight'];
        $init_money         = $template['init_money'];
        $increase_weight    = $template['increase_weight'];
        $increase_money     = $template['increase_money'];
        //首重
        $money              = $init_money;
        if( $weight > $init_weight ) {
            //续重
            if( $increase_weight > 0 )  {
                $less_weight    = ceil($weight - $init_weight);
                $less_n         = bcdiv((string)$less_weight, (string)$increase_weight,1);
                $less_n         = ceil($less_n);
                $less_money     = bcmul((string)$less_n, (string)$increase_money,2);
                $money          = bcadd((string)$money, (string)$less_money,2);
            }
        }
        return $money;
    }
    
    /**
     * 获取价格最高的运费模板（最高规则：首重价格 + 续重价格/kg）        
     * @param array $template
     * @param array $needTemplateIds
     * @param $weight
     */
    public function getMostHighFreightMoney( array $templateList = [] , array $needTemplateIds = [] ) 
    {
//        if( empty($templateList) ) {
//            return Normal::returnCode(Normal::FAIL,"默认价格模板未配置，请联系管理员处理[100000]");
//        }
//        
//        if( empty($needTemplateIds) ) {
//            return Normal::returnCode(Normal::FAIL,"默认价格模板未配置，请联系管理员处理[100001]");
//        }
        
        $freight_template_ids = array_unique($needTemplateIds);
        //获取当前商品分组的运费模板情况
        $current_template_list = [];
        foreach ($freight_template_ids as $key => $template_id )
        {
            if ( isset($templateList[$template_id]) ) {
                $current_template_list[$template_id] = $templateList[$template_id];
            }
            unset($freight_template_ids[$key]);
        }
        
//        if( empty($current_template_list) ) {
//            return Normal::returnCode(Normal::FAIL,"默认价格模板未配置，请联系管理员处理[100002]");
//        }
        
        //获取运费综合值最大的一个模板
        $price_template=[];
        if ($current_template_list){
            $price_arr      = array_column($current_template_list,null,'freight_all');
            $max_price      = max(array_keys($price_arr));
            $price_template = $price_arr[$max_price];
        }
        
        return Normal::returnCode(Normal::SUC,"运费模板获取成功",$price_template);
    }
    
    /**
     * 通过第三方接口获取省市区信息
     * 获取运费模板配置信息
     * 加入缓存hash
     * @param array $param
     * @return mixed
     */
    public function getDeliveryAddressInfoByAddress( array $param = [] )
    {
        $addressDetail = implode(" ",[
            $param['province'],
            $param['city'],
            $param['district'],
            $param['receiveAddress']
        ]);
        
        $regions = CacheProviderService::getCacheByHashList(self::USER_ADDRESS_CACHE_KEY,$addressDetail);
        if( !empty($regions) ) {
            return Normal::returnCode(Normal::SUC,"获取地址成功",$regions);
        }

        return Normal::returnCode(Normal::SUC,'获取地址成功',[
            'province'  => $param['province'],
            'city'      => $param['city'],
            'district'  => $param['district']
        ]);

        $res = GaoDeAddressApiClient::instance()->queryRegionByAddress(['address'=>$addressDetail]);
        if( !empty($res['geocodes']) ) 
        {
            $regions = current($res['geocodes']);
            //特殊处理
            if( empty($regions['city']) ) {
                $regions['city'] = $regions['district'];
            }
    
            //特殊处理
            if( empty($regions['district']) ) {
                $regions['district'] = $param['district'];
            }
    
            if( empty($regions['province']) || !is_string($regions['province']) ) {
                return Normal::returnCode(Normal::FAIL,"地址服务解析失败，请检查收货地址【{$param['receiveAddress']}】是否正确");
            }
            if( empty($regions['city']) || !is_string($regions['city']) ) {
                return Normal::returnCode(Normal::FAIL,"地址服务解析失败，请检查收货地址【{$param['receiveAddress']}】是否正确");
            }
            if( empty($regions['district']) || !is_string($regions['district']) ) {
                return Normal::returnCode(Normal::FAIL,"地址服务解析失败，请检查收货地址【{$param['receiveAddress']}】是否正确");
            }
            
            $regions = [
                'province'  => $regions['province'],
                'city'      => $regions['city'],
                'district'  => $regions['district']
            ];
            
            CacheProviderService::cacheByHashList(self::USER_ADDRESS_CACHE_KEY,$addressDetail,$regions);
            return Normal::returnCode(Normal::SUC,"获取地址成功",$regions);
        }
        return Normal::returnCode(Normal::FAIL,"地址服务解析失败，请检查收货地址【{$addressDetail}】是否正确");
    }
}